package ks.server.controllers.commands.admin.plugin;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.plugin.Plugin;
import ks.managers.user.UserManager;
import ks.server.ServerContext;
import ks.server.controllers.requests.PluginsRequest;
import ks.server.ipc.Listener;
import ks.server.persist.PersistentPluginManager;

/**
 * 
 */
public class PluginSuspendController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public PluginSuspendController (Communicator com) {
		this.com = com;
	}
	
	public boolean process(Message m) {
		String originator = m.getOriginator();
		UserManager um = ServerContext.getUserManager();
		
		if (originator == null) {
			System.err.println("Message originator is null.");
			return false;
		}
		if (!um.getUser(originator).isAdmin()) {
			Message r = Listener.nack(m, 4, "Access denied.");
			r.setRecipient(originator);
			com.distribute(r);
			return false;
		}
		
		Node pluginSuspendNode = m.contents();
		
		if (pluginSuspendNode == null || !pluginSuspendNode.getNodeName().equals("plugin-suspend")) {
			Message r = Listener.nack(m, 4, "No plugin-suspend element detected.");
			r.setRecipient(originator);
			com.distribute(r);
			return false;
		}
		
		NamedNodeMap nnp = pluginSuspendNode.getAttributes();
		Node pluginNode = nnp.getNamedItem("plugin");
		
		if (pluginNode == null) {
			Message r = Listener.nack(m, 4, "No plugin attribute detected.");
			r.setRecipient(originator);
			com.distribute(r);
			return false;
		}
		
		String pluginName = pluginNode.getNodeValue();
		PersistentPluginManager pm = ServerContext.getPluginManager();
		
		Plugin plugin = pm.getPlugin(pluginName);
		
		if (plugin == null) {
			Message r = Listener.nack(m, 4, "Plugin, " + pluginName + ", does not exist.");
			r.setRecipient(originator);
			com.distribute(r);
			return false;
		}
		
		plugin.suspend();
		pm.updatePlugin(pluginName);
		
		new PluginsRequest(com).send(pm.getList());
		
		Message r = Listener.ack(m, "Plugin suspended.");
		r.setRecipient(originator);
		com.distribute(r);
		
		return true;
	}
}
